<template>
	<view>
		<!-- <view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">
			{{ajax.loadText}}</view> -->
		<view class="box-1" id="list-box">
			<view class="talk-list">
				<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
					<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
						<image :src="item.pic" mode="aspectFill" class="pic"></image>
						<view class="content" @tap="copy(item)"  v-if="item.content"><text >{{item.content}}</text></view>
						<view class="content error" v-else>{{msg}}</view>
						<button v-if="item.share==1" :data-title="item.title" class="share-pic" open-type="share"><u-icon name="zhuanfa"></u-icon></button>
					</view>
				</view>
			</view>
		</view>
		<view class="box-2">
			<view class="flex_col tipx">
				<view class="keyword">
					<span @click="gsk('1')">重置聊天</span>
					<span @click="gsk('2')">我要赞赏</span>
					<span @click="gsk('3')">去除广告</span>
					<span @click="gsk('4')">加开发者</span>
					<span @click="gsk('5')">了解更多</span>
					</view>
			</view>
			<view class="flex_col">
				<view class="flex_grow">
					<textarea type="text" :disabled="disabled"   class="content" v-model="content" placeholder="请输入聊天内容"
						placeholder-style="color:#DDD;" :cursor-spacing="6"></textarea>
				</view>
				<button :disabled="disabled" class="send" @tap="send">发送</button>
			</view>
		</view>
		<!--button class="shareBtn" type="default" data-name="shareBtn" open-type="share"> 
		<u-icon name="zhuanfa"></u-icon>分享
		</button-->

		<u-popup v-model="popupShow" mode="bottom" border-radius="14">
			<view class="wechat-login">
				<view class="wechat-title">
					<image class="wx" src="@/static/myIcon/wechat.png" mode="aspectFit"></image>
					<text class="title">微信账号授权登录</text>
				</view>
				<u-button type="success" @click="wxLogin">确认</u-button>
			</view>
		</u-popup>
			
	</view>
</template>

<script>
	export default {
		data() {
			return {
				talkList: [],
				disabled:false,
				ajax: {
					rows: 20, //每页数量
					page: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '',
				popupShow: false, //微信授权弹窗
				userInfo: uni.getStorageSync('userInfo'),
				msg:'',//错误信息
				word:'',
				asknum:0,//统计咨询次数
				adnum:0,//0表示不看广告
				website:'https://chatgpt.online.2wex.com',//域名
				platform:'',//平台
				id:0,//回答id
				ads:{
					1:'',//激励广告
					2:'adunit-913c287512ccbe9e',//横屏广告
					3:'',//插屏广告
				},
				zanImg:'',
				zanshow:false,
				
				
			}
		},
		mounted() {
			var data = {
				"id": new Date().getTime(),
				"content": '您好，我是ChatGPT AI智能助手，可以跟你聊天，可以帮助你写作，可以帮助你翻译，可以帮你解决生活中烦恼，有什么问题就告诉我吧。\n（无限制免费聊天）\n ',
				"type": 2,
				"share":0,
				"pic": "/static/myIcon/logo.png"
			}
			uni.hideLoading();
			this.talkList.push(data);

			var data = {
				"id": new Date().getTime(),
				"content": '使用技巧：\n1. 第一次对话请描述清楚你要的东西，不要直接让它写论文或者文章，而是应该把问题拆分开来问，这样会更清晰的获取你要的内容。\n2. 回复：重置聊天，可以开启新的对话逻辑，让AI重新根据新的提问开始回答。',
				"type": 2,
				"share":0,
				"pic": "/static/myIcon/logo.png"
			}
			uni.hideLoading();
			this.talkList.push(data);
			if(this.content){
				this.send()
			}
			this.$nextTick(() => {
				// this.getHistoryMsg();
				
				
			});
		},
		onLoad: function(option){
			console.log(option)
			this.getAdnum();
			//this.getads(2);
			//this.getads(3);
			//this.getImage();
			if(option.word && option.word!=''){
				this.content = option.word;
			}
			wx.getSystemInfo({
			  success: (res) => {
			  	// windows | mac为pc端
			  	// android | ios为手机端
			    console.log('getSystemInfo：', res.platform);
				this.platform = res.platform;
			  }
			});
			
			
		},
		onShow() {
			let that = this
			this.timer = setInterval(function() {
						// 放入你自己的业务逻辑代码
						var id = parseInt(that.id);
						if(id!=0){
							that.getanswer();
						}
				}, 3000);
		},
		
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				// this.getHistoryMsg();
			}
		},
		onShareAppMessage(res) {
			console.log('res:',res)
			var word = res.from=='button'? res.target.dataset.title : this.word;
			var t = (word=='') ? '快来一起体验全球最火的ChatGPT智能AI吧！' : "我刚才问了全球最火ChatGPT智能AI一个问题，快来看看它是怎么回答的吧！";
			return {
				title:t,
				path:"/pages/index/index?word="+word
			};
		},
		methods: {
			// 获取广告配置
			getAdnum(){
				var adnum = 0;
				let t = this;
				if(uni.getStorageSync('adnum')){
					adnum = uni.getStorageSync('adnum');
					this.adnum = adnum;
					console.log('adnum:',adnum);
				}else{
					uni.request({
						url: this.website+"/ga/getnum",
						method: "get",
						success:function(res){
							adnum = parseInt(res.data.data);
							uni.setStorageSync('adnum', res.data
								.data);
							t.adnum = adnum;
							console.log('adnum:',adnum);
						}
						})
					
				}
				
			},
			// 获取广告
			getads(type){
				let that = this
				uni.request({
					url: this.website+"/ga/index",
					method: "get",
					data:{type:type},
					success:function(res){
						if(res.statusCode==200){
							that.ads[type] = res.data.data;
						}
						if(parseInt(type)==3){
							uni.setStorageSync('chapingad',res.data.data);
						}
					}
					})
			},
			// 获取历史消息
			getHistoryMsg() {
				if (!this.ajax.flag) {
					return; //
				}

				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					//let data = await this.joinHistoryMsg();
		
					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';
					/*
					if (this.ajax.page > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.talkList[0].id}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						selector = `#msg-${data[data.length-1].id}`;
					}
					
					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];
					*/
					selector = `#msg-${this.talkList[0].id}`;
					// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);
						
						/*
						this.hideLoadTips(true);
						
						if (data.length < this.ajax.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.ajax.page++;

							// 延迟 200ms ，以保证设置窗口滚动已完成
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200)
						}
						*/

					})
				}
				get();
			},
			// 拼接历史记录消息，正式项目可替换为请求历史记录接口
			joinHistoryMsg() {
				let join = () => {
					let arr = [];

					//通过当前页码及页数，模拟数据内容
					let startIndex = (this.ajax.page - 1) * this.ajax.rows;
					let endIndex = startIndex + this.ajax.rows;
					for (let i = startIndex; i < endIndex; i++) {
						arr.push({
							"id": i, // 消息的ID
							"content": `这是历史记录的第${i+1}条消息`, // 消息内容
							"type": Math.random() > 0.5 ? 1 : 0, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
							"pic": "/static/logo.png" // 头像
						})
					}

					/*
						颠倒数组中元素的顺序。将最新的数据排在本次接口返回数据的最后面。
						后端接口按 消息的时间降序查找出当前页的数据后，再将本页数据按消息时间降序排序返回。
						这是数据的重点，因为页面滚动条和上拉加载历史的问题。
					 */
					arr.reverse();

					return arr;
				}

				// 此处用到 ES6 的 Promise 知识，不懂的请自行学习。
				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 ajax 即可。
					setTimeout(() => {
						let data = join();
						done(data);
					}, 1500);
				})
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			//方法名 需要有个按钮来执行该方法
			adLoad: function(key) {
					var t = this;
					// 在页面中定义激励视频广告
					let videoAd = null
					uni.showLoading({
						title: '请稍等...'
					})
					uni.request({
						url: this.website+"/ga/index",
						data:{},
						success(res) {
							console.log(res)
							if(res.statusCode==200){
								// 在页面onLoad回调事件中创建激励视频广告实例
								if (wx.createRewardedVideoAd) {
								  videoAd = wx.createRewardedVideoAd({
								    adUnitId: res.data.data
								  })
								  videoAd.onLoad(() => {})
								  videoAd.onError((err) => {
									  t.serr(err.errMsg+':'+err.errCode);
								  })
								  videoAd.onClose((res) => {
									  // 用户点击了【关闭广告】按钮
									  if (res && res.isEnded) {
										// 正常播放结束，可以下发游戏奖励
										console.log('正常播放完毕，发送奖励')
										t.asknum = 0;
										//取消广告
										t.reward();
									  } else {
										// 播放中途退出，不下发游戏奖励
										console.log('中途退出，不发奖励')
										//t.reward();
									  }
								  })
								}
								
								// 用户触发广告后，显示激励视频广告
								if (videoAd) {
								  videoAd.show().catch(() => {
								    // 失败重试
								    videoAd.load()
								      .then(() => videoAd.show())
								      .catch(err => {
								        console.log('激励视频 广告显示失败')
										t.serr('激励视频 广告显示失败');
								      })
								  })
								}
								
							}
						},
						complete() {
							setTimeout(() => {
								uni.hideLoading()
							}, 2000)
			
						}
					})
			},
			//奖励
			reward:function(){
				this.userInfo = uni.getStorageSync('userInfo');
				let openid =   this.userInfo.openid || '';
				let that = this;
				uni.request({
					url: this.website+"/ga/reward",
					data:{openid:openid},
					success(res) {
						that.asknum = 0;
						that.send();
					}
					})
				
			},
			//记录错误
			serr(msg){
				uni.request({
					url: this.website+"/ga/gaserr",
					data:{msg:msg},
					success(res) {
						
					}
					})
				//如果拉取错误的话，就直接给他奖励
				this.asknum = this.asknum-1;
				this.send();
			},
			// 发送信息
			send() {
				var asknum = parseInt(this.asknum);
				var adnum = parseInt(this.adnum);
				console.log(asknum,adnum,this.platform)
				if(asknum && asknum>=adnum && this.platform!='devtools'){
					if(this.platform=='windows' || this.platform=='mac'){
						uni.showToast({
							title: '请使用手机端打开！',
							duration: 2000
						});
						return;

					}
					this.adLoad();
					return;
				}
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}
				this.disabled = true;
				// uni.showLoading({
				// 	title: "AI正在作答..." 
				// })
				let data = {
					"id": new Date().getTime(),
					"content": this.content,
					"type": 1,
					"pic": "/static/myIcon/logo.png"
				}
				this.talkList.push(data);
				let data2 = {
					"id": 1000,
					"content": '系统正在提交问题...',
					"type": 2,
					"pic": "/static/myIcon/logo.png"
				}
				this.talkList.push(data2);
				this.userInfo = uni.getStorageSync('userInfo');
				let openid =   this.userInfo.openid || '';
				//this.getHistoryMsg();
				let that = this;
				setTimeout(() => {
					// 将当前发送信息 添加到消息列表。
					uni.request({
						url: this.website+"/chat/ask",
						method: "POST",
						data:{word:this.content,openid:openid},
						success: (res) => {
							//this.disabled = false;
							console.log(res.data.data)
							let data = {
								"id": new Date().getTime(),
								"content": res.data.data,
								"type": 2,
								"title": that.word,
								"share":res.data.code==0 ? 1 : 0,
								"pic": "/static/myIcon/logo.png"
							}
							if(res.data.code==1){
								this.msg = res.data.msg;
								this.disabled = false;
								uni.hideLoading();
								this.talkList.pop();
								this.talkList.push(data);
								
							}else if(openid){
								var isok = res.data.isok ? parseInt(res.data.isok) : 0;
								if(isok){
									that.asknum = 0;
								}else{
									var num = parseInt(res.data.num);
									if(asknum>num){
										that.asknum = asknum+1;
									}else{
										that.asknum = res.data.num;
									}
									
								}
								console.log(that.asknum)
							}
							if(res.data.code==0){
								this.disabled = false;
								uni.hideLoading();
								this.talkList.pop();
								this.talkList.push(data);
							}else if(res.data.code==2){
								that.id = res.data.data;
							}
							
						},
						fail:function(){
							let data = {
								"id": new Date().getTime(),
								"content": '[机器人睡着了，请再次提问唤醒他~]',
								"type": 2,
								"share":0,
								"pic": "/static/myIcon/logo.png"
							}
							uni.hideLoading();
							this.talkList.push(data);
						}
					})

					this.$nextTick(() => {
						// 清空内容框中的内容
						this.word = this.content;
						this.content = '';
						uni.pageScrollTo({
							scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
							duration: 0
						});
					})
				}, 1500);
			},
			copy: function(item) {
				if(!item.content) return;
				uni.showModal({
					title: '复制内容',
					content: item.content,
					confirmText: '复制',
					success: function(res) {
						if (res.confirm) {
							uni.setClipboardData({
								data: item.content,
								success: () => { //复制成功的回调函数
									uni.showToast({ //提示
										title: '复制成功'
									})
								}
							});
							
						} else if (res.cancel) {
							
						}
					}
				});
			},
			//查询结果
			getanswer(){
				let that = this
				uni.request({
					url: this.website+"/chat/getanswer",
					method: "get",
					data:{id:this.id},
					success:function(res){
						if(res.data.code==0){
							that.disabled = false;
							//已回答
							console.log('answer:',res.data.data);
							console.log('answer:',res);
							let data = {
								"id": new Date().getTime(),
								"content": res.data.data,
								"type": 2,
								"title": that.word,
								"share":res.data.code==0 ? 1 : 0,
								"pic": "/static/myIcon/logo.png"
							}
							
							that.id = 0;
							uni.hideLoading();
							that.talkList.pop();
							that.talkList.push(data);
						
							
						}else if(res.data.code==2){
							that.disabled = false;
							//参数错误，重新提问
							let data = {
								"id": new Date().getTime(),
								"content": res.data.msg,
								"type": 2,
								"title": that.word,
								"share": 0,
								"pic": "/static/myIcon/logo.png"
							}
							
							that.id = 0;
							that.asknum = that.asknum>0 ? parseInt(that.asknum)-1 : 0; 
							uni.hideLoading();
							that.talkList.pop();
							that.talkList.push(data);
						
						}else{
							that.disabled = false;
							//等待回答
							var t = parseInt(res.data.data)>0 ? "[ID:"+that.id+"]您提问正在排队...\n当前位置："+res.data.data+"，请耐心等待..." : "AI正在给你解答，请稍后...\n\n如果超时会自动重置排序.";
							let data = {
								"id": new Date().getTime(),
								"content": t,
								"type": 2,
								"title": that.word,
								"share": 0,
								"pic": "/static/myIcon/logo.png"
							}
							uni.hideLoading();
							that.talkList.pop();
							that.talkList.push(data);
						}
						
					}
				})
			},
			gsk(type){
				switch(type){
					case '1':
					this.content = '重置聊天';
					this.send();
					break;
					case '2':
					uni.reLaunch({
						url:'/pages/mine/index?zan=1'
					})
					break;
					case '3':
					this.content = '去广告';
					this.send();
					break;
					case '4':
					uni.reLaunch({
						url:'/pages/mine/index?zan=2'
					})
					break;
					case '5':
					this.content = '了解更多内容';
					this.send();
					break;
				}
			},
			getImage() {
				uni.request({
					url: this.website+'/wxapp/getzan',
					method: 'GET',
					success: (res) => {
						this.zanImg = res.data;
						
					}
				})
			},
			
		}
	}
</script>

<style lang="scss">
	@import "../../lib/global.scss";

	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}
	.flex_col.tipx{
		height: 30px;
	}
	.keyword span{
		border-radius: 2px;
		background: #2196F3;
		padding: 2px;
		font-size: 14px;
		color: #fff;
		margin-right: 10px;
	}
	.shareBtn{
		    width: 80px;
		    height: 80px;
		    line-height: 80px;
		    border-radius: 50%;
		    background: #2196F3;
		    color: #ffffff;
		    position: fixed;
		    right: 20px;
		    top: 20%;
	}
	.share-pic{
		margin: 0;
		background: none;
		font-size: 18px;
	}
	.content{
		word-wrap: break-word;
		word-break: normal;
	}
	.error{
		color: #f00;
	}
	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 150rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 0;
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 115rpx;
		}

		.content {
			background-color: #fff;
			height: 100rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #42b983;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 30rpx;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #a0e959;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}
</style>
